<template>
  <div class="consultations-container">
    <div class="page-header">
      <h2>健康咨询管理</h2>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="医生">
          <el-select v-model="filterForm.doctorId" placeholder="选择医生" clearable>
            <el-option
              v-for="doctor in doctors"
              :key="doctor.id"
              :label="doctor.name"
              :value="doctor.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
            <el-option label="待回复" value="pending" />
            <el-option label="已回复" value="replied" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-table
      v-loading="loading"
      :data="consultations"
      style="width: 100%"
      class="consultation-table"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="医生" width="120">
        <template #default="{ row }">
          {{ getDoctorName(row.doctorId) }}
        </template>
      </el-table-column>
      <el-table-column label="患者" width="120">
        <template #default="{ row }">
          {{ getPatientName(row.patientId) }}
        </template>
      </el-table-column>
      <el-table-column label="最新消息" min-width="200">
        <template #default="{ row }">
          <div class="last-message">
            <div class="message-content">{{ getLastMessage(row).content }}</div>
            <div class="message-time">{{ formatTime(getLastMessage(row).time) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row)">{{ getStatusText(row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleView(row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 对话详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="咨询详情"
      width="60%"
      class="consultation-dialog"
    >
      <div class="chat-container" v-loading="loading">
        <div class="chat-messages" ref="chatMessages">
          <div
            v-for="msg in currentConsultation?.messages"
            :key="msg.id"
            :class="['message-item', msg.sender === 'admin' ? 'admin' : 'user']"
          >
            <div class="message-avatar">
              <img
                :src="msg.sender === 'admin' ? adminAvatar : userAvatar"
                :alt="msg.sender === 'admin' ? '管理员' : '用户'"
              />
            </div>
            <div class="message-content">
              <div class="message-text">{{ msg.content }}</div>
              <div class="message-time">{{ formatTime(msg.time) }}</div>
            </div>
          </div>
        </div>
        <div class="chat-input">
          <el-input
            v-model="replyContent"
            type="textarea"
            :rows="3"
            placeholder="请输入回复内容"
          />
          <el-button
            type="primary"
            @click="handleReply"
            :disabled="!replyContent.trim()"
          >发送回复</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { getDoctors, getUsers, getConsultations, sendMessage } from '@/api/consultation'

export default {
  name: 'AdminConsultations',
  setup() {
    const loading = ref(false)
    const consultations = ref([])
    const doctors = ref([])
    const users = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const dialogVisible = ref(false)
    const currentConsultation = ref(null)
    const replyContent = ref('')
    const chatMessages = ref(null)

    const filterForm = ref({
      doctorId: '',
      status: ''
    })

    const adminAvatar = 'https://img.icons8.com/color/48/000000/administrator-male.png'
    const userAvatar = 'https://img.icons8.com/color/48/000000/user-male-circle--v2.png'

    // 获取医生名称
    const getDoctorName = (doctorId) => {
      const doctor = doctors.value.find(d => d.id === doctorId)
      return doctor ? doctor.name : '未知医生'
    }

    // 获取患者名称
    const getPatientName = (patientId) => {
      const user = users.value.find(u => u.id === patientId)
      return user ? user.username : '未知用户'
    }

    // 获取最新消息
    const getLastMessage = (consultation) => {
      const messages = consultation.messages || []
      return messages[messages.length - 1] || { content: '无消息', time: '' }
    }

    // 格式化时间
    const formatTime = (time) => {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    }

    // 获取状态文本
    const getStatusText = (consultation) => {
      const lastMessage = getLastMessage(consultation)
      return lastMessage.sender === 'admin' ? '已回复' : '待回复'
    }

    // 获取状态类型
    const getStatusType = (consultation) => {
      const lastMessage = getLastMessage(consultation)
      return lastMessage.sender === 'admin' ? 'success' : 'warning'
    }

    // 加载数据
    const loadData = async () => {
      try {
        loading.value = true
        const [doctorsRes, usersRes, consultationsRes] = await Promise.all([
          getDoctors(),
          getUsers(),
          getConsultations({
            page: currentPage.value,
            pageSize: pageSize.value
          })
        ])
        doctors.value = doctorsRes.data
        users.value = usersRes.data
        consultations.value = consultationsRes.data
        total.value = consultationsRes.total
      } catch (error) {
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }

    // 筛选
    const handleFilter = () => {
      currentPage.value = 1
      loadData()
    }

    // 重置筛选
    const resetFilter = () => {
      filterForm.value = {
        doctorId: '',
        status: ''
      }
      handleFilter()
    }

    // 分页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadData()
    }

    // 页码改变
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadData()
    }

    // 查看详情
    const handleView = (consultation) => {
      currentConsultation.value = consultation
      dialogVisible.value = true
      replyContent.value = ''
      // 滚动到底部
      setTimeout(() => {
        if (chatMessages.value) {
          chatMessages.value.scrollTop = chatMessages.value.scrollHeight
        }
      }, 100)
    }

    // 发送回复
    const handleReply = async () => {
      if (!replyContent.value.trim()) return

      try {
        loading.value = true
        await sendMessage({
          doctorId: currentConsultation.value.doctorId,
          patientId: currentConsultation.value.patientId,
          content: replyContent.value,
          sender: 'admin'
        })
        ElMessage.success('回复成功')
        replyContent.value = ''
        // 重新加载数据
        await loadData()
        // 更新当前对话
        const updatedConsultation = consultations.value.find(
          c => c.id === currentConsultation.value.id
        )
        if (updatedConsultation) {
          currentConsultation.value = updatedConsultation
        }
      } catch (error) {
        ElMessage.error('回复失败')
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      loadData()
    })

    return {
      loading,
      consultations,
      doctors,
      users,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      currentConsultation,
      replyContent,
      chatMessages,
      filterForm,
      adminAvatar,
      userAvatar,
      getDoctorName,
      getPatientName,
      getLastMessage,
      formatTime,
      getStatusText,
      getStatusType,
      handleFilter,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      handleView,
      handleReply
    }
  }
}
</script>

<style scoped>
.consultations-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.consultation-table {
  margin-bottom: 20px;
}

.last-message {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.message-content {
  color: #333;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.consultation-dialog {
  .chat-container {
    display: flex;
    flex-direction: column;
    height: 500px;
  }

  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f7f9fb;
  }

  .message-item {
    display: flex;
    margin-bottom: 20px;
    gap: 12px;

    &.admin {
      flex-direction: row-reverse;

      .message-content {
        align-items: flex-end;
      }

      .message-text {
        background: #409eff;
        color: #fff;
      }
    }
  }

  .message-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .message-content {
    display: flex;
    flex-direction: column;
    gap: 4px;
    max-width: 70%;
  }

  .message-text {
    padding: 10px 16px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .message-time {
    font-size: 12px;
    color: #999;
  }

  .chat-input {
    padding: 20px;
    background: #fff;
    border-top: 1px solid #eee;
    display: flex;
    gap: 12px;

    .el-input {
      flex: 1;
    }
  }
}
</style> 